"""
递归
数字累加和
"""


def sum_numbers(num):
    if num == 1:
        return 1
    return num + sum_numbers(num - 1)


sum_result = sum_numbers(3)
print(sum_result)

"""
lambda 表达式
lambada 参数列表: 具有返回值的表达式
"""


# 函数
def fn1():
    return 200


print(fn1)
print(fn1())

# lambda表达式
fn2 = lambda: 100
print(fn2)
print(fn2())

# 计算a+b
fn3 = lambda a, b: a + b
print(fn3(1, 3))

# 默认参数
fn4 = lambda a, b, c=100: a + b + c
print(fn4(1, 2))

# 可变参数 *args
fn5 = lambda *args: args
print(fn5(1, 6, 2, 3, 5, 4))

# 可变参数 **kwargs
fn6 = lambda **kwargs: kwargs
print(fn6(name='小明', age=18))

# 数字比大小
fn7 = lambda a, b: a if a > b else b
print(fn7(2, 3))

students = [
    {'name': 'TOM', 'age': 20},
    {'name': 'ROSE', 'age': 19},
    {'name': 'JACK', 'age': 21}
]

# 按name值升序排序
students.sort(key=lambda x: x['name'])
print(students)

# 按name值倒叙排列
students.sort(key=lambda x: x['name'], reverse=True)
print(students)

"""
高阶函数：将一个函数当作另一个函数的参数
abs()绝对值
round()四舍五入
"""


def add_num1(a, b):
    return abs(a) + abs(b)


print(add_num1(-3, 3))


def add_num2(a, b):
    return round(a) + round(b)


print(add_num2(1.2, 3.6))


def add_num3(a, b):
    return round(abs(a)) + round(abs(b))


print(add_num3(-1.2, 3.6))

"""
内置高阶函数
map()
reduce()
filter()
"""

list1 = [1, 2, 3, 4, 5, 6]


def func1(x):
    """
    计算各个参数的二次方
    :param x:
    :return:
    """
    return x ** 2


result = map(func1, list1)
print(result)
print(list(result))

import functools


def func2(a, b):
    return a + b


result = functools.reduce(func2, list1)
print(result)


def func3(x):
    """
    得到偶数
    :param x:
    :return:
    """
    return x % 2 == 0


result = filter(func3, list1)
print(result)
print(list(result))
